package cn.cellcom.agent.online.dispatcher;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
import java.util.Set;

import cn.cellcom.agent.common.AgentConstant;
import cn.cellcom.agent.online.client.AgentClient;
import cn.cellcom.agent.online.client.ClientManager;
import cn.cellcom.agent.online.wrapper.SessionWrapper;

/**
 * 
 * @author chenxb
 * 
 */
public abstract class AbstractAgentSelector implements IAgentSelector {
	public AgentClient bestAgentFrom(SessionWrapper session, Comparator<AgentClient> compare) {
		List<AgentClient> validateList = new ArrayList<AgentClient>();
		Set<AgentClient> agents = ClientManager.getInstance().getOnlineAgents(session.getPid());
		if(agents != null) {
			for (AgentClient ac : agents) {
				boolean validate = this.validateAgent(ac, session);
				if (validate) {
					validateList.add(ac);
				}
			}
		}
		if (validateList.size() == 0) {
			return null;
		}

		Collections.sort(validateList, compare);
		int size = validateList.size() - 1;
		return validateList.get(size);
	}

	/**
	 * 1、当前聊天数量小于最大聊天数量<br>
	 * 2、状态处于在线
	 */
	public boolean validateAgent(AgentClient agent, SessionWrapper session) {
		// 如果坐席没有登陆这个技能组,则认为无效
		if (agent.getGroups().get(session.getGroup().getId()) == null) {
			return false;
		}
		// 如果坐席已经和访客在通话,则直接有效
		if (agent.getIdMap().get(session.getSession().getCrm()) != null) {
			return true;
		}
		int cnt = agent.getCurrentChat();
		int max = agent.getAgentConfig().getMaxChat();
		boolean health = cnt < max;
		if (!health) {
			return false;
		}
		return agent.getAgentConfig().getStatus().equals(AgentConstant.AGENT_STATUS.ONLINE);
	}
}
